//
//  setNoteViewController.swift
//  issac-note
//
//  Created by Issac on 16/9/6.
//  Copyright © 2016年 Issac. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class setNoteViewController: UIViewController,UITextFieldDelegate, UITextViewDelegate {

    //MARK: - Property
    @IBOutlet var note_title: UITextField!
    @IBOutlet var note_content: UITextView!
    @IBOutlet var rightBarBtn: UIBarButtonItem!
    @IBOutlet var loading: UIActivityIndicatorView!
    
    
    var uid: String?
    var delegate: SendNoticeDelegate?
    var isSetNote: Bool = false
    
    //MARK: - ClassFunc
    override func viewDidLoad() {
        super.viewDidLoad()
        
        note_title.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
        note_title.leftViewMode = UITextFieldViewMode.Always
        
        let letfBarBtn = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(backToListView))
        self.navigationItem.leftBarButtonItem = letfBarBtn
        
        note_title.returnKeyType = UIReturnKeyType.Next
        note_title.tag = 1
        note_title.delegate = self
        
        note_content.delegate = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - IBAction
    @IBAction func syncNotetoServer(sender: UIBarButtonItem) {
        
        if(
            note_title.text == nil ||
            note_content.text == nil
        ) {
        
           self.alertTipAction("日志还没有写完呢")
            
        }else {
        
            self.loading.startAnimating()
            self.syncDataToServer()
        
        }
        
    }
    
    @IBAction func finishEditingContent(sender: UIBarButtonItem) {
    
        if(sender.title != " ") {
        
            sender.title = " "
            self.note_content.resignFirstResponder()
            self.note_title.resignFirstResponder()
            
        }
        
    }
    
    
    //MARK: - GetDateFormServer
    func syncDataToServer(){
    
        let url: String = "http://issac.website/issac-noteBackstage/Admin/index/insertNote"
        let parameters = [
            "uid" : self.uid!,
            "title" : self.note_title.text!,
            "ctt" : self.note_content.text!
        ]
        
        Alamofire.request(.POST, url, parameters: parameters).responseJSON { (response) in
            
            switch response.result {
                
            case .Success:
                
                if let value = response.result.value {
                    
                    let json = JSON(value)
                    let status = json["status"] ?true :false;
                    
                    self.handleServerResult(status)
                    
                }
                
            case .Failure:
                
                self.alertTipAction("网络错误，请稍后再试")
                
            }
            
        }
        
    }
    
    //MARK: - MyselfFunction
    func alertTipAction(message: String?){
    
        let alertAction = UIAlertController(title: "新建日志", message: message, preferredStyle: .Alert)
        let cancelAction = UIAlertAction(title: "确定", style: .Cancel, handler: nil)
        
        alertAction.addAction(cancelAction)
        self.presentViewController(alertAction, animated: true, completion: nil)
        
        
    }
    func backToListView(){
        
        if self.delegate != nil {
            
            self.delegate?.sendNotice(self.isSetNote)
            self.navigationController?.popViewControllerAnimated(true)
            
        }
        
    }
    func handleServerResult(sender: Bool){
    
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(loadingToshowResult), userInfo: nil, repeats: false)
        
    }
    
    func loadingToshowResult(sender: Bool){
    
        self.loading.stopAnimating()
        if !sender {
            
            self.alertTipAction("同步成功")
            self.isSetNote = true
            
        }else {
            
            self.alertTipAction("同步失败，请稍后再试");
            
        }
        
    }


    //MARK: - Delegate
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        if(textField.tag == 1){
            
            note_content.becomeFirstResponder()
            
        }
        
        return true
        
    }
    
    func textViewDidBeginEditing(textView: UITextView) {
        
        self.rightBarBtn.title = "完成"
        
    }
    
    
}
